{% extends 'base.html' %}
{% load static %}

{% block title %}积分商城 - 本地有约{% endblock %}

{% block extra_css %}
<style>
    .points-header {
        background: var(--gradient-success);
        color: white;
        padding: 3rem 0;
        margin-bottom: 2rem;
    }
    
    .my-points-card {
        background: white;
        border-radius: 1.5rem;
        padding: 2rem;
        box-shadow: var(--shadow-lg);
        text-align: center;
    }
    
    .points-value {
        font-size: 4rem;
        font-weight: 700;
        background: var(--gradient-primary);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .product-card {
        background: white;
        border-radius: 1rem;
        overflow: hidden;
        box-shadow: var(--shadow-md);
        transition: all 0.3s ease;
        height: 100%;
    }
    
    .product-card:hover {
        transform: translateY(-10px);
        box-shadow: var(--shadow-lg);
    }
    
    .product-image {
        height: 200px;
        overflow: hidden;
        position: relative;
    }
    
    .product-image img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
    }
    
    .product-card:hover .product-image img {
        transform: scale(1.1);
    }
    
    .product-badge {
        position: absolute;
        top: 1rem;
        right: 1rem;
        background: var(--danger-color);
        color: white;
        padding: 0.25rem 0.75rem;
        border-radius: 2rem;
        font-size: 0.85rem;
        font-weight: 600;
    }
    
    .points-price {
        font-size: 1.75rem;
        font-weight: 700;
        color: var(--primary-color);
    }
    
    .stock-info {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        background: var(--light-bg);
        border-radius: 2rem;
        font-size: 0.85rem;
    }
</style>
{% endblock %}

{% block content %}
<!-- 积分头部 -->
<div class="points-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-8">
                <h1><i class="fas fa-gift"></i> 积分商城</h1>
                <p class="lead">用积分兑换心仪的奖品</p>
            </div>
            <div class="col-md-4">
                {% if user.is_authenticated %}
                <div class="my-points-card">
                    <div class="points-value">{{ user.points }}</div>
                    <p class="mb-0">我的积分</p>
                    <a href="{% url 'points:records' %}" class="btn btn-sm btn-outline-primary mt-2">
                        <i class="fas fa-history"></i> 积分记录
                    </a>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<div class="container mb-5">
    <!-- 分类筛选 -->
    <div class="mb-4">
        <ul class="nav nav-pills justify-content-center">
            <li class="nav-item">
                <a class="nav-link active" href="#" data-type="" onclick="filterProducts(''); return false;">
                    全部商品
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-type="voucher" onclick="filterProducts('voucher'); return false;">
                    <i class="fas fa-ticket-alt"></i> 优惠券
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-type="privilege" onclick="filterProducts('privilege'); return false;">
                    <i class="fas fa-crown"></i> 平台特权
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-type="physical" onclick="filterProducts('physical'); return false;">
                    <i class="fas fa-box"></i> 实物奖品
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#" data-type="virtual" onclick="filterProducts('virtual'); return false;">
                    <i class="fas fa-gem"></i> 虚拟物品
                </a>
            </li>
        </ul>
    </div>
    
    <!-- 商品列表 -->
    <div class="row" id="productsContainer">
        <div class="col-12 text-center py-5">
            <div class="loader"></div>
        </div>
    </div>
</div>

<!-- 兑换确认模态框 -->
<div class="modal fade" id="exchangeModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认兑换</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <img id="modalProductImage" src="" class="img-fluid rounded" style="max-height: 200px;">
                </div>
                <h5 id="modalProductName" class="text-center mb-3"></h5>
                
                <div class="alert alert-info">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span>所需积分：</span>
                        <strong id="modalProductPoints" class="text-primary"></strong>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span>当前积分：</span>
                        <strong>{{ user.points }}</strong>
                    </div>
                    <hr>
                    <div class="d-flex justify-content-between align-items-center">
                        <span>剩余积分：</span>
                        <strong id="modalRemainingPoints"></strong>
                    </div>
                </div>
                
                <div class="mb-3">
                    <label class="form-label-custom">兑换数量</label>
                    <input type="number" class="form-control form-control-custom" id="exchangeQuantity" value="1" min="1">
                </div>
                
                <div id="addressForm" style="display: none;">
                    <div class="mb-3">
                        <label class="form-label-custom">收货人</label>
                        <input type="text" class="form-control form-control-custom" id="receiverName" placeholder="请输入收货人姓名">
                    </div>
                    <div class="mb-3">
                        <label class="form-label-custom">联系电话</label>
                        <input type="tel" class="form-control form-control-custom" id="receiverPhone" placeholder="请输入联系电话">
                    </div>
                    <div class="mb-3">
                        <label class="form-label-custom">收货地址</label>
                        <textarea class="form-control form-control-custom" id="receiverAddress" rows="2" placeholder="请输入详细收货地址"></textarea>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-gradient-success" onclick="confirmExchange()">
                    <i class="fas fa-check"></i> 确认兑换
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let products = [];
    let selectedProduct = null;
    let currentFilter = '';
    
    // 加载商品列表
    function loadProducts() {
        API.points.getProducts({ status: 'available' })
            .then(response => {
                products = response.data.results || response.data;
                renderProducts(products);
            })
            .catch(error => {
                document.getElementById('productsContainer').innerHTML = `
                    <div class="col-12 text-center text-danger">
                        <i class="fas fa-exclamation-circle fa-3x mb-3"></i>
                        <p>加载商品失败，请刷新页面重试</p>
                    </div>
                `;
            });
    }
    
    // 渲染商品列表
    function renderProducts(productsToRender) {
        const container = document.getElementById('productsContainer');
        
        if (productsToRender.length === 0) {
            container.innerHTML = `
                <div class="col-12">
                    <div class="empty-state">
                        <i class="fas fa-shopping-bag"></i>
                        <h3>暂无商品</h3>
                        <p>敬请期待更多精彩商品</p>
                    </div>
                </div>
            `;
            return;
        }
        
        container.innerHTML = productsToRender.map(product => `
            <div class="col-md-6 col-lg-3 mb-4">
                <div class="product-card">
                    <div class="product-image">
                        <img src="${product.image || '/static/img/default-product.jpg'}" alt="${product.name}">
                        ${product.stock < 10 && product.stock > 0 ? 
                            `<span class="product-badge">仅剩${product.stock}件</span>` : 
                            product.stock === 0 ? '<span class="product-badge bg-secondary">已兑完</span>' : ''
                        }
                    </div>
                    <div class="p-3">
                        <h5 class="mb-2">${product.name}</h5>
                        <p class="text-muted small mb-3">${product.description.substring(0, 60)}...</p>
                        
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div class="points-price">
                                <i class="fas fa-coins"></i> ${product.points_required}
                            </div>
                            <span class="stock-info">
                                库存 ${product.stock}
                            </span>
                        </div>
                        
                        <div class="d-grid">
                            ${product.stock > 0 ? 
                                `<button class="btn btn-gradient-primary" onclick="openExchangeModal(${product.id})">
                                    <i class="fas fa-shopping-cart"></i> 立即兑换
                                </button>` :
                                `<button class="btn btn-secondary" disabled>已兑完</button>`
                            }
                        </div>
                        
                        <div class="text-center mt-2">
                            <small class="text-muted">已兑换 ${product.exchange_count} 次</small>
                        </div>
                    </div>
                </div>
            </div>
        `).join('');
    }
    
    // 筛选商品
    function filterProducts(type) {
        currentFilter = type;
        
        // 更新导航样式
        document.querySelectorAll('.nav-pills .nav-link').forEach(link => {
            link.classList.remove('active');
        });
        event.target.classList.add('active');
        
        // 筛选商品
        const filtered = type ? products.filter(p => p.type === type) : products;
        renderProducts(filtered);
    }
    
    // 打开兑换模态框
    function openExchangeModal(productId) {
        {% if not user.is_authenticated %}
        window.location.href = '{% url "users:login" %}?next={{ request.path }}';
        return;
        {% endif %}
        
        selectedProduct = products.find(p => p.id === productId);
        if (!selectedProduct) return;
        
        // 检查积分是否足够
        const userPoints = {{ user.points|default:0 }};
        if (userPoints < selectedProduct.points_required) {
            showError('积分不足，无法兑换');
            return;
        }
        
        // 填充模态框内容
        document.getElementById('modalProductImage').src = selectedProduct.image || '/static/img/default-product.jpg';
        document.getElementById('modalProductName').textContent = selectedProduct.name;
        document.getElementById('modalProductPoints').textContent = selectedProduct.points_required + ' 积分';
        document.getElementById('modalRemainingPoints').textContent = (userPoints - selectedProduct.points_required) + ' 积分';
        
        // 如果是实物商品，显示地址表单
        const addressForm = document.getElementById('addressForm');
        if (selectedProduct.type === 'physical') {
            addressForm.style.display = 'block';
        } else {
            addressForm.style.display = 'none';
        }
        
        // 重置数量
        document.getElementById('exchangeQuantity').value = 1;
        document.getElementById('exchangeQuantity').max = selectedProduct.stock;
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('exchangeModal'));
        modal.show();
    }
    
    // 确认兑换
    function confirmExchange() {
        const quantity = parseInt(document.getElementById('exchangeQuantity').value);
        
        if (quantity < 1 || quantity > selectedProduct.stock) {
            showError('兑换数量无效');
            return;
        }
        
        const data = {
            quantity: quantity
        };
        
        // 如果是实物商品，需要填写地址
        if (selectedProduct.type === 'physical') {
            const name = document.getElementById('receiverName').value.trim();
            const phone = document.getElementById('receiverPhone').value.trim();
            const address = document.getElementById('receiverAddress').value.trim();
            
            if (!name || !phone || !address) {
                showError('请填写完整的收货信息');
                return;
            }
            
            data.receiver_name = name;
            data.receiver_phone = phone;
            data.receiver_address = address;
        }
        
        API.points.exchange(selectedProduct.id, data)
            .then(response => {
                showSuccess('兑换成功！');
                bootstrap.Modal.getInstance(document.getElementById('exchangeModal')).hide();
                
                // 刷新页面以更新积分
                setTimeout(() => {
                    location.reload();
                }, 1500);
            })
            .catch(error => {
                showError(error.response?.data?.message || '兑换失败，请重试');
            });
    }
    
    // 页面加载时加载商品
    document.addEventListener('DOMContentLoaded', loadProducts);
</script>
{% endblock %}
